package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

//演示文件拷贝

func main() {
	_, err := CopyFile("D:\\下载\\尚硅谷Go语言\\笔记\\笔记\\1.txt", "D:\\new.txt")
	if err != nil {
		fmt.Printf("拷贝文件失败  %v", err)
		return
	}
	fmt.Println("拷贝文件成功")
}

//CopyFile 拷贝源文件到目标文件
func CopyFile(srcFileName string, dstFileName string) (written int64, err error) {

	//打开源文件
	srcFile, err := os.Open(srcFileName)
	if err != nil {
		return 0, err
	}
	reader := bufio.NewReader(srcFile)

	//打开目标文件 只写，不存在则创建
	dstFile, err := os.OpenFile(dstFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		return 0, err
	}
	writer := bufio.NewWriter(dstFile)

	return io.Copy(writer, reader)
}
